package com.jieshuibao.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.jieshuibao.common.config.Const;
import com.jieshuibao.common.config.Global;
import com.jieshuibao.mapper.AdvisoryMapper;
import com.jieshuibao.mapper.AdvisoryRecordingMapper;
import com.jieshuibao.mapper.AdvisoryUserMapper;
import com.jieshuibao.mapper.AnswerUserMapper;
import com.jieshuibao.mapper.CounselorMapper;
import com.jieshuibao.mapper.QuestionMapper;
import com.jieshuibao.mapper.QuestionUserMapper;
import com.jieshuibao.mapper.SecretlyMapper;
import com.jieshuibao.mapper.UserDealRecordExMapper;
import com.jieshuibao.mapper.UserDealRecordMapper;
import com.jieshuibao.mapper.UserExMapper;
import com.jieshuibao.mapper.UserMapper;
import com.jieshuibao.mapper.VideoBuyHistoryMapper;
import com.jieshuibao.model.db.Advisory;
import com.jieshuibao.model.db.AdvisoryRecording;
import com.jieshuibao.model.db.AdvisoryUser;
import com.jieshuibao.model.db.AdvisoryUserExample;
import com.jieshuibao.model.db.Answer;
import com.jieshuibao.model.db.Counselor;
import com.jieshuibao.model.db.Question;
import com.jieshuibao.model.db.QuestionUserKey;
import com.jieshuibao.model.db.Secretly;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.db.UserDealRecord;
import com.jieshuibao.model.db.UserDealRecordExample;
import com.jieshuibao.model.db.VideoBuyHistory;
import com.jieshuibao.model.db.AdvisoryUserExample.Criteria;
import com.jieshuibao.model.domain.RefundProduct;
import com.jieshuibao.util.IdGen;
import com.jieshuibao.util.JsonUtil;
import com.jieshuibao.util.MoneyRandom;
import com.jieshuibao.util.PayTypeUtil;
import com.jieshuibao.util.StringUtils;
import com.jieshuibao.util.UUIDGenerator;
import com.jieshuibao.util.push.PushType;
import com.jieshuibao.wx.util.PayCommonUtil;


@Service
public class UserDealRecordService{
	private static final String appId = "8aaf07086619653001661b1865b301fa";
	private static final Logger logger = LoggerFactory
			.getLogger("UserDealRecordService.class");
	
	@Resource
	private UserDealRecordMapper userDealRecordMapper;
	@Resource
	private UserDealRecordExMapper userDealRecordExMapper;
	
	@Resource
	private UserExMapper userExMapper;
	
	@Resource
	private UserMapper UserMapper;
	@Resource
	private SecretlyMapper secretlyMapper;
	
	@Resource
	private QuestionUserMapper questionUserMapper;
	
	@Resource
	private AnswerUserMapper answerUserMapper;
	
	@Resource
	private QuestionMapper questionMapper;
	
	@Resource
	private SecretlyService secretlyService;
	
	@Resource
	private IntegralService integralService;
	
	@Resource
	private VideoBuyHistoryMapper videoBuyHistoryMapper;
	
	@Resource
	private AdvisoryMapper advisoryMapper;
	
	@Resource
	private AdvisoryUserMapper advisoryUserMapper;
	
	@Resource
	private AdvisoryRecordingMapper advisoryRecordingMapper;
	
	@Resource
	private SmsSendService smsSendService;
	
	@Resource
	private CounselorMapper counselorMapper;
	
	@Resource
	private PushService pushService;
	
	@Value("${price.num}")
	private int priceNum;
	
	@Resource
	private WxRefundService wxRefundService;
	
	@Resource
	private RedisService redisService;
	
	public void addUserDealRecord(UserDealRecord userDealRecord) {
		userDealRecordMapper.insertSelective(userDealRecord);
	}
	
	public void delUserDealRecordByUuid(String uuid) {
		userDealRecordMapper.deleteByPrimaryKey(uuid);
	}
	
	public void updateUserDealRecord(UserDealRecord userDealRecord) {
		userDealRecordMapper.updateByPrimaryKeySelective(userDealRecord);
	}
	
	public UserDealRecord getUserDealRecordByUuid(String uuid) {
		return userDealRecordMapper.selectByPrimaryKey(uuid);
	}
	
	public List<UserDealRecord> getPageUserDealRecord(UserDealRecordExample userDealRecordExample) {
		return userDealRecordMapper.selectPage(userDealRecordExample);
	}
	
	public int countUserDealRecord(UserDealRecordExample userDealRecordExample) {
		return userDealRecordMapper.countByExample(userDealRecordExample);
	}
	public void addUserDealRecords(List<UserDealRecord> userDealRecords){
		userDealRecordExMapper.insertIntoUserDealRecord(userDealRecords);
	}
	//小鸟
	public Double getUserdealRecordsByExample(UserDealRecordExample userDealRecordExample){
		return userDealRecordExMapper.selectSumMoneyByExample(userDealRecordExample);
	}
	
	//用户收入、支出 总计
	
	public Double getSumIncome(UserDealRecordExample userDealRecordExample){
		return userDealRecordExMapper.selectSumIncome(userDealRecordExample);
	}
	
	
	// 用户支出  解税宝收入流水
	/**
	 * 用户支出 解税宝收入流水
	 * @param userId
	 * @param productId
	 * @param payType
	 * @param money
	 * @param goodsType
	 * @param goodsName
	 */
	public  void userdealRecordRunning(String userId,String productId,String payType,double money,String goodsType,String goodsName){
		
		try {
			UserDealRecord userDealRecord1 = new UserDealRecord();//用户支出
			UserDealRecord userDealRecord2 = new UserDealRecord();//解税宝收入
			String uuid1 = IdGen.uuid();
			String uuid2 = IdGen.uuid();
			Date date = new Date();
			
			userDealRecord1.setUuid(uuid1);
			userDealRecord1.setUserId(userId);
			userDealRecord1.setAccountType(PayTypeUtil.ACCOUNTTYPE_PERSONAL);
			userDealRecord1.setBusinessNo(productId);
			userDealRecord1.setCreateDate(date);
			userDealRecord1.setGoodsType(goodsType);
			userDealRecord1.setPaySucTime(date);
			userDealRecord1.setPayType(payType);
			userDealRecord1.setRealPrice(money);
			userDealRecord1.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			userDealRecord1.setSum(money);
			userDealRecord1.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
			
			logger.info("业务名称："+goodsName+":用户支出流水:"
					+ JsonUtil.toJson(userDealRecord1));
			userDealRecordMapper.insertSelective(userDealRecord1);
			userDealRecord2.setUuid(uuid2);
			userDealRecord2.setUserId(PayTypeUtil.COMPANY_ACCPUNT);
			userDealRecord2.setAccountType(PayTypeUtil.ACCOUNTTYPE_BUSINESS);
			userDealRecord2.setBusinessNo(productId);
			userDealRecord2.setCreateDate(date);
			userDealRecord2.setGoodsType(goodsType);
			userDealRecord2.setPaySucTime(date);
			userDealRecord2.setPayType(payType);
			userDealRecord2.setRealPrice(money);
			userDealRecord2.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			userDealRecord2.setSum(money);
			userDealRecord2.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
			
			logger.info("业务名称："+goodsName+":解税宝收入流水:"
					+ JsonUtil.toJson(userDealRecord2));
			userDealRecordMapper.insertSelective(userDealRecord2);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("业务名称："+goodsName+":解税宝流水异常:"
					+ JsonUtil.toJson(productId));
		}
		
	}
	
	/**
	 * 用户围观流水
	 * @param userId
	 * @param productId
	 * @param payType
	 * @param money
	 */
	public void onLookRunning(String userId,String productId,String payType,double money){
		try {
			Secretly secretly2 = secretlyMapper.selectByPrimaryKey(productId);
			if (secretly2!=null) {
				String questionUuid = secretly2.getQuestionUuid();
				
				if (payType.equals(PayTypeUtil.PAYTYPE_BALANCE)) {
					User user = new User();
					user.setPhoneNumber(userId);
					user.setBalance(-money);
					userExMapper.updateUserAdvisoryNum(user);
					
				}else if (payType.equals(PayTypeUtil.PAYTYPE_VIPBALANCE)) {
					User user = new User();
					user.setPhoneNumber(userId);
					user.setVipBalance(-money);
					userExMapper.updateUserAdvisoryNum(user);
				}else if (payType.equals(PayTypeUtil.PAYTYPE_WEIXIN)) {
					Secretly secretly = new Secretly();
					secretly.setUuid(productId);
					secretly.setPayStatus(PayCommonUtil.PAYSUCCESS_STATUS);
					secretlyMapper.updateByPrimaryKeySelective(secretly);
					
				}
				QuestionUserKey questionUserKey = new QuestionUserKey();
				questionUserKey.setQuestionUuid(questionUuid);
				questionUserKey.setPhoneNumber(userId);
				questionUserMapper.insertSelective(questionUserKey);
				userdealRecordRunning(userId,productId,payType,money,PayTypeUtil.GOODSTYPE_SECRETLY,PayTypeUtil.GOODSTYPE_SECRETLY_DESS);
				//围观达到一定条件，给咨询师和用户分账  
				questionAskReplyJsb(questionUuid,money,productId);
				//用户积分增加
				integralService.integral(userId, "secretly", 1);
			}else {
				logger.info("用户围观流水业务id错误："
						+ JsonUtil.toJson(productId));
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("用户围观流水异常"
					+ JsonUtil.toJson(productId));
		}
		
		
		
		
	}
	/**
	 * 咨询流水
	 * v2.0
	 * @param userId
	 * @param productId
	 * @param payType
	 * @param money
	 */
	public void updateAdviosyRunning(String userId,String productId,String payType,double money){
		try {
			Advisory advisory = advisoryMapper.selectByPrimaryKey(productId);
			
			if (advisory!=null) {
				
				String userRes = advisory.getUserRes();
				String userAsk = advisory.getUserAsk();
				
				String onlyId = advisory.getOnlyId();
				
				Counselor counselor = userExMapper.selectCounseleorByPhone(userRes);
				if(counselor!=null){
					Integer advNum = counselor.getAdvNum();
					
					Integer advScore = counselor.getAdvScore();
					
					counselor.setAdvNum(advNum+1);
					
					counselor.setAdvScore(advScore+5);
					
				}
				AdvisoryUserExample advisoryUserExample = new AdvisoryUserExample();
				Criteria createCriteria = advisoryUserExample.createCriteria();
				createCriteria.andOnlyIdEqualTo(onlyId);
				long currentTimeMillis = System.currentTimeMillis();
				int i = advisoryUserMapper.countByExample(advisoryUserExample);
				AdvisoryUser advisoryUser1 = new AdvisoryUser();//发起者
				AdvisoryUser advisoryUser2 = new AdvisoryUser();//接受者
				if(i==0){
					String uuid1 = UUIDGenerator.getUUID();//聊天流水记录表
					String uuid2 = UUIDGenerator.getUUID();
					advisoryUser1.setUuid(uuid1);
					advisoryUser1.setUserOne(userAsk);
					advisoryUser1.setUserOther(userRes);
					advisoryUser1.setOnlyId(onlyId);
					advisoryUser1.setMessage("你好！");
					advisoryUser1.setLastTime(currentTimeMillis);
					advisoryUser1.setType(Const.ADVISORY_USER_TYPE_0);
					
					advisoryUser2.setUuid(uuid2);
					advisoryUser2.setUserOne(userRes);
					advisoryUser2.setUserOther(userAsk);
					advisoryUser2.setOnlyId(onlyId);
					advisoryUser2.setMessage("你好！");
					advisoryUser2.setLastTime(currentTimeMillis);
					advisoryUser2.setType(Const.ADVISORY_USER_TYPE_1);
				}else {
					List<AdvisoryUser> list = advisoryUserMapper.selectByExample(advisoryUserExample);
					advisoryUser1 = list.get(0);
					advisoryUser2 = list.get(1);
					advisoryUser1.setMessage("你好！");
					advisoryUser1.setLastTime(currentTimeMillis);
					
					advisoryUser2.setMessage("你好！");
					advisoryUser2.setLastTime(currentTimeMillis);
					String userOne1 = advisoryUser1.getUserOne();
					
					if(userOne1.equals(userAsk)){
						advisoryUser1.setType(Const.ADVISORY_USER_TYPE_0);
						advisoryUser2.setType(Const.ADVISORY_USER_TYPE_1);
					}else {
						advisoryUser1.setType(Const.ADVISORY_USER_TYPE_1);
						advisoryUser2.setType(Const.ADVISORY_USER_TYPE_0);
					}
					
				}
				AdvisoryRecording advisoryRecording = new AdvisoryRecording();
				String uuid3 = UUIDGenerator.getUUID();
				advisoryRecording.setUuid(uuid3);
				advisoryRecording.setUserId(userAsk);
				advisoryRecording.setAdvisoryId(productId);
				advisoryRecording.setOnlyId(onlyId);
				advisoryRecording.setType(Const.ADVISORY_RECORDING_STATUS_1);
				advisoryRecording.setChatTime(currentTimeMillis);
				advisoryRecording.setContent("你好！");
				if (payType.equals(PayTypeUtil.PAYTYPE_BALANCE)) {
					User user = new User();
					user.setPhoneNumber(userId);
					user.setBalance(-money);
					userExMapper.updateUserAdvisoryNum(user);
					
				}else if (payType.equals(PayTypeUtil.PAYTYPE_VIPBALANCE)) {
					User user = new User();
					user.setPhoneNumber(userId);
					user.setVipBalance(-money);
					userExMapper.updateUserAdvisoryNum(user);
				}else if (payType.equals(PayTypeUtil.PAYTYPE_WEIXIN)) {
					Advisory advisory2 = new Advisory();
					advisory2.setUuid(productId);
					advisory2.setPayStatus(PayCommonUtil.PAYSUCCESS_STATUS);
					advisoryMapper.updateByPrimaryKeySelective(advisory2);
					
					
				}
				
				advisoryRecordingMapper.insertSelective(advisoryRecording);
				
				if(i==0){
					advisoryUserMapper.insertSelective(advisoryUser1);
					advisoryUserMapper.insertSelective(advisoryUser2);
				}else {
					advisoryUserMapper.updateByPrimaryKeySelective(advisoryUser1);
					advisoryUserMapper.updateByPrimaryKeySelective(advisoryUser2);
				}
				counselorMapper.updateByPrimaryKeySelective(counselor);
				
				userdealRecordRunning(userId,productId,payType,money,PayTypeUtil.GOODSTYPE_ADVISORY,PayTypeUtil.GOODSTYPE_ADVISORY_DESS);
				User user = UserMapper.selectByPrimaryKey(userRes);
				if (user!=null) {
					String phone = user.getPhone();
					User userA = UserMapper.selectByPrimaryKey(userAsk);
					String userAskName = "";
					if(userA != null){
						userAskName = StringUtils.isBlank(userA.getRealName()) ? userA.getPhone().substring(0, 3) + "****" + userA.getPhone().substring(7, 4) : userA.getRealName();
						smsSendService.sendNotify(appId, phone, Const.SCENE_ADVISORY_COUNSELOR, new String[]{userAskName});
						//推送给咨询师
						pushService.pushAlias(PushType.MODEL_4, new String[]{userAsk,userAskName,userAsk}, userRes, "1");
					}else{
						logger.info("推送消息时，提问者不存在");
					}
				}
			}else {
				logger.info("一对一流水业务id错误："
						+ JsonUtil.toJson(productId));
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("一对一流水异常"
					+ JsonUtil.toJson(productId));
		}
		
		
		
		
	}
	
	
	/**
	 * 视频支付流水
	 * @param userId
	 * @param productId
	 * @param payType
	 * @param money
	 */
	public void videoRunning(String userId,String productId,String payType,double money){
		try {
			VideoBuyHistory videoBuyHistory = videoBuyHistoryMapper.selectByPrimaryKey(productId);
			if (videoBuyHistory!=null) {
				if (payType.equals(PayTypeUtil.PAYTYPE_BALANCE)) {
					User user = new User();
					user.setPhoneNumber(userId);
					user.setBalance(-money);
					userExMapper.updateUserAdvisoryNum(user);
					
				}else if (payType.equals(PayTypeUtil.PAYTYPE_VIPBALANCE)) {
					User user = new User();
					user.setPhoneNumber(userId);
					user.setVipBalance(-money);
					userExMapper.updateUserAdvisoryNum(user);
				}else if (payType.equals(PayTypeUtil.PAYTYPE_WEIXIN)) {
					VideoBuyHistory videoBuyHistory2 = new VideoBuyHistory();
					videoBuyHistory2.setId(productId);
					videoBuyHistory2.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
					videoBuyHistoryMapper.updateByPrimaryKeySelective(videoBuyHistory2);
					
				}
			
				userdealRecordRunning(userId,productId,payType,money,PayTypeUtil.GOODSTYPE_VIDEO_SINGLE,PayTypeUtil.GOODSTYPE_VIDEO_SINGLE_DESS);
			
				//用户积分增加
				integralService.integral(userId, "video", 1);
			}else {
				logger.info("用户视频支付流水业务id错误："
						+ JsonUtil.toJson(productId));
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("用户视频支付流水异常"
					+ JsonUtil.toJson(productId));
		}
		
		
		
		
	}
	
	
	
	
	
	/**
	 * 围观达到一定条件给回答者 提问者 分账 
	 *  提问者流水  收入
	 *  回答者流水 收入
	 *  解税宝流水 支出
	 */
	public void questionAskReplyJsb(String quuid,double money,String productId){
		
		try {
			Question question = questionMapper.selectByPrimaryKey(quuid);
			if (question==null) {
				logger.info("围观达到一定条件给回答者 提问者 分账 问题id错误:"
						+ JsonUtil.toJson(quuid));
				return;
			}
			String annoStatus = question.getAnnoStatus();
			//上过最热或者推荐
			if (StringUtils.isNotBlank(annoStatus)&&annoStatus.equals("0")) {
				
				String phoneNum = question.getPhoneNum();
				double sumMoneyUser = secretlyService.getSumMoneyUser(phoneNum, quuid);
				Integer qumoney = question.getMoney();
				Integer addMoney = question.getAddMoney();
				if (addMoney!=null) {
					qumoney=qumoney+addMoney;
				}
				User user = new User();
				//咨询师分账比例
				double subMoney = MoneyRandom.getSubMoney(qumoney);
				if (sumMoneyUser>subMoney) {
					//围观收入大于补贴咨询师的钱 开始分账
					double subMoneyFifteen = MoneyRandom.getSubMoneyFifteen(money);
					double ttkAskMoney = MoneyRandom.getTtkAskMoney(money);
					List<Answer> answers = answerUserMapper.selectAnswerApproveNum(quuid, 2);
					Date date = new Date();
					
					if (answers!=null&&answers.size()>0) {
						Answer answer = answers.get(0);
						String phoneNumber = answer.getPhoneNumber();
						
						UserDealRecord userDealRecord3 = new UserDealRecord();//回答用户收入
						String uuid3 = IdGen.uuid();
						userDealRecord3.setUuid(uuid3);
						userDealRecord3.setUserId(phoneNumber);
						userDealRecord3.setAccountType(PayTypeUtil.ACCOUNTTYPE_PERSONAL);
						userDealRecord3.setBusinessNo(productId);
						userDealRecord3.setCreateDate(date);
						userDealRecord3.setGoodsType(PayTypeUtil.GOODSTYPE_SECRETLY);
						userDealRecord3.setPaySucTime(date);
						userDealRecord3.setPayType(PayTypeUtil.PAYTYPE_BALANCE);
						userDealRecord3.setRealPrice(subMoneyFifteen);
						userDealRecord3.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
						userDealRecord3.setSum(subMoneyFifteen);
						userDealRecord3.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
						logger.info("业务名称：围观:回答用户收入流水:"
								+ JsonUtil.toJson(userDealRecord3));
						userDealRecordMapper.insertSelective(userDealRecord3);
						user.setPhoneNumber(phoneNumber);
						user.setBalance(subMoneyFifteen);
						//用余额增加
						logger.info("业务名称：围观:回答用户增加余额:"
								+ JsonUtil.toJson(user));
						userExMapper.updateUserAdvisoryNum(user);
						
					}else {
						subMoneyFifteen=0;
					}
					
					
					UserDealRecord userDealRecord1 = new UserDealRecord();//提问用户收入
					UserDealRecord userDealRecord2 = new UserDealRecord();//解税宝支出
					String uuid1 = IdGen.uuid();
					String uuid2 = IdGen.uuid();
					
					userDealRecord1.setUuid(uuid1);
					userDealRecord1.setUserId(phoneNum);
					userDealRecord1.setAccountType(PayTypeUtil.ACCOUNTTYPE_PERSONAL);
					userDealRecord1.setBusinessNo(productId);
					userDealRecord1.setCreateDate(date);
					userDealRecord1.setGoodsType(PayTypeUtil.GOODSTYPE_SECRETLY);
					userDealRecord1.setPaySucTime(date);
					userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_BALANCE);
					userDealRecord1.setRealPrice(ttkAskMoney);
					userDealRecord1.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
					userDealRecord1.setSum(ttkAskMoney);
					userDealRecord1.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
					
					logger.info("业务名称：围观:提问用户收入流水:"
							+ JsonUtil.toJson(userDealRecord1));
					userDealRecordMapper.insertSelective(userDealRecord1);
					
					
					user.setPhoneNumber(phoneNum);
					user.setBalance(subMoneyFifteen);
					//用余额增加
					logger.info("业务名称：围观:提问用户增加余额:"
							+ JsonUtil.toJson(user));
					userExMapper.updateUserAdvisoryNum(user);
					
					userDealRecord2.setUuid(uuid2);
					userDealRecord2.setUserId(PayTypeUtil.COMPANY_ACCPUNT);
					userDealRecord2.setAccountType(PayTypeUtil.ACCOUNTTYPE_BUSINESS);
					userDealRecord2.setBusinessNo(productId);
					userDealRecord2.setCreateDate(date);
					userDealRecord2.setGoodsType(PayTypeUtil.GOODSTYPE_SECRETLY);
					userDealRecord2.setPaySucTime(date);
					userDealRecord2.setPayType(PayTypeUtil.PAYTYPE_COMPANYENVELOPES);
					userDealRecord2.setRealPrice(subMoneyFifteen+ttkAskMoney);
					userDealRecord2.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
					userDealRecord2.setSum(subMoneyFifteen+ttkAskMoney);
					userDealRecord2.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
					
					logger.info("业务名称：围观:解税宝支出流水:"
							+ JsonUtil.toJson(userDealRecord2));
					userDealRecordMapper.insertSelective(userDealRecord2);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("围观达到一定条件给回答者 提问者 分账 异常:"
					+ JsonUtil.toJson(quuid));
		}
		
		
	}
	/**
	 * 支出收入流水-通用
	 * @param userId 用户ID
	 * @param productId 业务主键
	 * @param payType 支付类型
	 * @param money 金额
	 * @param goodsType 商品类型
	 * @param goodsName 业务名称
	 * @param inAnOutRows {key:'in',value:'账号类型-个人/公司',key:'out',value:'账号类型-个人/公司'} key：in表示收入方,out表示支出方
	 * @return
	 */
	public  boolean userdealRecordCommonRunning(String userId,String productId,String payType,double money,String goodsType,String goodsName,Map<String, Object> inAnOutRows){
		try {
			UserDealRecord userDealRecord = new UserDealRecord();//流水
			Date date = new Date();
			//key：in（收入）   value：账户类型-个人/企业
			//key：out（支出）  value：账户类型-个人/企业
			for(String key:inAnOutRows.keySet()){
				System.out.println("Key: "+key+" Value: "+inAnOutRows.get(key));
				if(!PayTypeUtil.ACCOUNTTYPE_BUSINESS.equals(inAnOutRows.get(key)) && 
						!PayTypeUtil.ACCOUNTTYPE_PERSONAL.equals(inAnOutRows.get(key))){
					logger.error("业务名称："+goodsName+":解税宝流水异常:map参数中，值不合法：必须是账号类型");
					return false;
				}
				if("in".equals(key)){
					userDealRecord.setUuid(IdGen.uuid());//流水主键
					userDealRecord.setUserId(PayTypeUtil.ACCOUNTTYPE_BUSINESS.equals(inAnOutRows.get(key)) ? 
							PayTypeUtil.COMPANY_ACCPUNT : userId);//用户   ACCOUNTTYPE_PERSONAL
					userDealRecord.setAccountType(inAnOutRows.get(key).toString());//账户类型 1企业2个人
					userDealRecord.setBusinessNo(productId);//业务编号
					userDealRecord.setCreateDate(date);//创建时间
					userDealRecord.setGoodsType(goodsType);//商品类型1：悬赏；2：偷偷看；3购买会员卡；4发红包
					userDealRecord.setPaySucTime(date);//支付成功时间
					userDealRecord.setPayType(payType);//支付类型：0 余额支付 1会员卡支付 2 企业会员卡支付 3 微信支付
					userDealRecord.setRealPrice(money);//实际价格（会员卡实际价格）
					userDealRecord.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
					userDealRecord.setSum(money);//总价
					userDealRecord.setTradeType(PayTypeUtil.TRDETYPE_INCOME);//交易类型1：支出；2：收入//PayTypeUtil.TRDETYPE_EXPENDITURE
				}else if("out".equals(key)){
					userDealRecord.setUuid(IdGen.uuid());
					userDealRecord.setUserId(PayTypeUtil.ACCOUNTTYPE_BUSINESS.equals(inAnOutRows.get(key)) ? 
							PayTypeUtil.COMPANY_ACCPUNT : userId);
					userDealRecord.setAccountType(inAnOutRows.get(key).toString());
					userDealRecord.setBusinessNo(productId);
					userDealRecord.setCreateDate(date);
					userDealRecord.setGoodsType(goodsType);
					userDealRecord.setPaySucTime(date);
					userDealRecord.setPayType(payType);
					userDealRecord.setRealPrice(money);
					userDealRecord.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
					userDealRecord.setSum(money);
					userDealRecord.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
				}else{
					logger.error("业务名称："+goodsName+":解税宝流水异常:" + JsonUtil.toJson(productId) + "map参数中，key值不合法：必须包含两个key：in/out");
					return false;
				}
				userDealRecordMapper.insertSelective(userDealRecord);
				
				StringBuffer logString = new StringBuffer("业务名称：" + goodsName + ":");
				logString.append(PayTypeUtil.ACCOUNTTYPE_PERSONAL.equals(userDealRecord.getAccountType()) ? "用户" : "解税宝");
				logString.append(PayTypeUtil.TRDETYPE_EXPENDITURE.equals(userDealRecord.getTradeType()) ? "支出" : "收入").append("流水:");
				
				logger.info(logString.toString() + JsonUtil.toJson(userDealRecord));
	        }
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("业务名称："+goodsName+":解税宝流水异常:" + JsonUtil.toJson(productId));
		}
		return true;
	}
	
	/**
	 * 用户退款流水
	 */
	public void addUserCompanyUserDealRecord(String pId, String goodsType,
			double money, String userId, String payType) {
		try {

			if (StringUtils.isNotBlank(goodsType)
					&& StringUtils.isNotBlank(pId)
					&& StringUtils.isNotBlank(userId)
					&& StringUtils.isNotBlank(payType) && money > 0) {

				RefundProduct refundProduct = new RefundProduct();
				refundProduct.setUuid(pId);
				refundProduct.setGoodsType(goodsType);
				User user = new User();
				user.setPhoneNumber(userId);
				refundProduct.setStatus(Global.SUCCESS);
				if (payType.equals(PayTypeUtil.PAYTYPE_WEIXIN)) {
					boolean b = this.userdealRecordRunning(userId, pId, payType,
							money, goodsType, "退款"+"商品类型："+goodsType,
							PayTypeUtil.TRDETYPE_INCOME, Const.ACCOUNTPERSON);
					// 解税宝流水
					boolean c = this.userdealRecordRunning(Const.JSBUSERID, pId,
							payType, money, goodsType, "退款"+"商品类型："+goodsType,
							PayTypeUtil.TRDETYPE_EXPENDITURE, Const.ACCOUNTCOMPANY);
						
						if (!c ||! b) {
							refundProduct.setErrorMessage("添加流水异常");
							logger.error("悬赏退款添加流水异常：" + pId);
						} 
					
				}else {
					//其他支付方式
					refundProduct.setErrorMessage("微信退款成功！添加流水时支付方式错误！");
				}
				wxRefundService.addBsbRefundAndUpdateProduct(null,
						refundProduct); // 结束悬赏
				redisService.delete(pId + "_num");
				logger.info("结束悬赏问题：" + pId);

			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(goodsType+"退款流水异常：" + e);
		}
	}
	
	/**
	 * 用户收入 解税宝支出
	 * 
	 * @param userId
	 *            用户i
	 * @param productId
	 *            业务id
	 * @param payType
	 *            支付方式
	 * @param money
	 *            金额
	 * @param goodsType
	 *            商品类型
	 * @param goodsName
	 *            商品名字
	 * @param tradeType
	 *            收入支出
	 * @param accountType
	 *            账号类型
	 */
	public boolean userdealRecordRunning(String userId, String productId,
			String payType, double money, String goodsType, String goodsName,
			String tradeType, String accountType) {

		try {

			if (StringUtils.isNotBlank(userId)
					&& StringUtils.isNotBlank(productId)
					&& StringUtils.isNotBlank(payType)
					&& StringUtils.isNotBlank(goodsType)
					&& StringUtils.isNotBlank(tradeType)
					&& StringUtils.isNotBlank(accountType) && money > 0) {

				UserDealRecord userDealRecord1 = new UserDealRecord();
				String uuid1 = IdGen.uuid();
				Date date = new Date();
				userDealRecord1.setUuid(uuid1);
				userDealRecord1.setUserId(userId);
				userDealRecord1.setAccountType(accountType);
				userDealRecord1.setBusinessNo(productId);
				userDealRecord1.setCreateDate(date);
				userDealRecord1.setGoodsType(goodsType);
				userDealRecord1.setPaySucTime(date);
				userDealRecord1.setPayType(payType);
				userDealRecord1.setRealPrice(money);
				userDealRecord1.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
				userDealRecord1.setSum(money);
				if (tradeType.equals(PayTypeUtil.TRDETYPE_INCOME)
						|| tradeType.equals(PayTypeUtil.TRDETYPE_EXPENDITURE)) {
					userDealRecord1.setTradeType(tradeType);
				} else {
					return false;
				}
				logger.info("业务名称：" + goodsName + ":用户流水:"
						+ JsonUtil.toJson(userDealRecord1));
				userDealRecordMapper.insertSelective(userDealRecord1);
				return true;
			} else {
				logger.info("用户id:" + userId + "业务id" + productId + "支付方式："
						+ payType + "商品类型：" + goodsType + "商品名字：" + goodsName
						+ "收入支出：" + tradeType + "账号类型：" + accountType + "支付金额："
						+ money);
				return false;

			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("业务名称：" + goodsName + ":解税宝流水异常:"
					+ JsonUtil.toJson(productId));
			return false;
		}

	}
}
